package com.quanyan.assets.repository;

import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.emun.StateType;
import com.quanyan.assets.entity.TbUserAssets;
import com.quanyan.assets.entity.TbUserAssetsExample;
import com.quanyan.assets.mapper.ETbUserAssetsMapper;
import com.quanyan.assets.mapper.TbUserAssetsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by wmb on 2016/6/24.
 */
@Repository
public class UserAssetsRepository {
    @Autowired
    private TbUserAssetsMapper tbUserAssetsMapper;
    @Autowired
    private ETbUserAssetsMapper eTbUserAssetsMapper;

    public TbUserAssets selectByUidAndAssetsType(Integer uid, byte assetsType) {
        TbUserAssetsExample tbUserAssetsExample = new TbUserAssetsExample();
        tbUserAssetsExample.createCriteria().andUidEqualTo(uid).andAssetsTypeEqualTo(assetsType);
        List<TbUserAssets> tbUserAssetsList = tbUserAssetsMapper.selectByExample(tbUserAssetsExample);
        if (tbUserAssetsList.isEmpty()) {
            TbUserAssets tbUserAssets = new TbUserAssets();
            tbUserAssets.setUid(uid);
            tbUserAssets.setAccumulate(0L);
            tbUserAssets.setUseableAmount(0);
            tbUserAssets.setAssetsType(assetsType);
            tbUserAssets.setState((byte) 1);
            try {
                tbUserAssetsMapper.insertSelective(tbUserAssets);
                return tbUserAssets;
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            return tbUserAssets;
        } else {
            return tbUserAssetsList.get(0);
        }
    }

    public int updateEffectiveAccumulate(Integer uid, Byte assetsType, Long accumulate) {
        return eTbUserAssetsMapper.updateEffectiveAccumulate(uid, assetsType, accumulate);
    }

    public void initAllCount(Integer uid) {
        for (AssetsType assetsType : AssetsType.values()) {
            TbUserAssetsExample tbUserAssetsExample=new TbUserAssetsExample();
            tbUserAssetsExample.createCriteria().andUidEqualTo(uid).andAssetsTypeEqualTo(assetsType.id.byteValue());
            List<TbUserAssets> tbUserAssetsList=tbUserAssetsMapper.selectByExample(tbUserAssetsExample);
            if(tbUserAssetsList.isEmpty()) {
                TbUserAssets tbUserAssets = new TbUserAssets();
                tbUserAssets.setUid(uid);
                tbUserAssets.setAssetsType(assetsType.id.byteValue());
                tbUserAssets.setState(StateType.EFFECTIVE.id.byteValue());
                try {
                    tbUserAssetsMapper.insertSelective(tbUserAssets);
                } catch (Exception e) {

                }
            }

        }

    }
}
